import { parse } from 'querystring';
import {AddressVO} from "@/types/common";

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// For the official demo site, it is used to turn off features that are not needed in the real development environment
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

export const toUnderline =(str:string):string => {
  return str.replace(/([A-Z])/g,"_$1").toUpperCase();
}

export function isArray(array:any) {
  return Object.prototype.toString.call(array) === '[object Array]';
}

/**
 * 数组转树形
 * @param nodes
 * @param options
 * @returns {*}
 */
export function arrayToTree(nodes:any, options:any = {}) {
  let i, l,
    key = options.idKey || 'id',
    parentKey = options.pIdKey || 'parentId',
    childKey = options.children || 'children';
  if (!nodes) return [];
  if (isArray(nodes)) {
    const r = [];
    const tmpMap = {};
    for (i = 0, l = nodes.length; i < l; i++) {
      tmpMap[nodes[i][key]] = nodes[i];
    }
    for (i = 0, l = nodes.length; i < l; i++) {
      if (tmpMap[nodes[i][parentKey]] && nodes[i][key] !== nodes[i][parentKey]) {
        if (!tmpMap[nodes[i][parentKey]][childKey])
          tmpMap[nodes[i][parentKey]][childKey] = [];
        tmpMap[nodes[i][parentKey]][childKey].push(nodes[i]);
      } else {
        r.push(nodes[i]);
      }
    }
    return r;
  } else {
    return [nodes];
  }
}

export const transformParams = (params:any,sorter:any) => {
  let orderBy='';
  const sortKeys=Object.keys(sorter);
  sortKeys.forEach((key,index)=>{
    const upperCaseKey=toUnderline(key);
    if(sorter[key]==='descend'){
      orderBy=orderBy+`${upperCaseKey} DESC`;
    }else{
      orderBy=orderBy+`${upperCaseKey} ASC`;
    }
    if(index!==sortKeys.length-1){
      orderBy=orderBy+',';
    }
  });
  if(orderBy){
    return {
      orderBy:orderBy,
      ...params
    }
  }
  return params;
}

export function getBase64(img: File|Blob, callback: (arg0: string | ArrayBuffer | null) => any) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export function renderAddress(address?:AddressVO):string {
  if(address){
    return address.provinceName + '/' + address.cityName + '/' + address.districtName + '/' + address.detailAddress
  }
  return '-';
}

